package vn.com.unit.springmvc.mvc;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import vn.com.unit.springmvc.domain.AssetType;
import vn.com.unit.springmvc.repo.AssetTypeDao;

@Controller
@RequestMapping("/view")
public class AssetTypeRestController
{
    @Autowired
    private AssetTypeDao assetTypeDao;

    @RequestMapping(method=RequestMethod.GET, produces="application/json")
    public @ResponseBody List<AssetType> listAllAssetTypes()
    {
        return assetTypeDao.findAllOrderedByName();
    }

//    @RequestMapping(method=RequestMethod.GET)
//    public String displaySortedAssetTypes(Model model)
//    {
//        model.addAttribute("newAssetType", new AssetType());
//        model.addAttribute("assetTypes", assetTypeDao.findAllOrderedByName());
//        return "index";
//    }
    
    
    @RequestMapping(value="/{id}", method=RequestMethod.GET)
    public String lookupAssetTypeById(@PathVariable("id") Long id, Model model)
    {
        AssetType obj = assetTypeDao.findById(id);
        model.addAttribute("newAssetType", obj);
        model.addAttribute("assetTypes", assetTypeDao.findAllOrderedByName());
        return "assettype";
    }
    
//    @RequestMapping(value="/delete/{id}", method=RequestMethod.GET)
//    public @ResponseBody String deleteAssetTypeById(@PathVariable("id") String id)
//    {
//         assetTypeDao.delete(id);
//         //return "index";
//         return "redirect:/";
//    }
    
    @RequestMapping(method = RequestMethod.POST)
	public String saveEditAssetType(
			@Valid @ModelAttribute("editAssetType") AssetType editAssetType,
			BindingResult result, Model model) {
		if (!result.hasErrors()) {
			AssetType obj = assetTypeDao.findById(editAssetType.getId());
			if (obj != null) {
				assetTypeDao.update(editAssetType);
			}
			return "redirect:/assettype";
		} else {
			model.addAttribute("isEdit", true);
			return "view_assettype";
		}

	}
}
